import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'dart:math' show Random;

class PracticePage extends StatefulWidget {
  const PracticePage({Key? key}) : super(key: key);

  @override
  State<PracticePage> createState() => _PracticePageState();
}

class _PracticePageState extends State<PracticePage> {
  final AudioPlayer _audioPlayer = AudioPlayer();
  int? _selectedIndex;
  bool _hasAnswered = false;
  int _correctAnswerIndex = 0;

  // 图片数据
  final List<String> _images = [
    'assets/images/lion.png',
    'assets/images/mosquito.png',
    'assets/images/penguin.png',
    'assets/images/tiger.png',
  ];

  // 添加当前题号和总题数
  int _currentQuestionIndex = 0;
  static const int _totalQuestions = 10;

  @override
  void initState() {
    super.initState();
    // 随机打乱图片顺序
    final random = Random();
    final indexes = List.generate(4, (index) => index);
    indexes.shuffle(random);
    
    final shuffledImages = indexes.map((i) => _images[i]).toList();
    _images.clear();
    _images.addAll(shuffledImages);
    
    // 更新正确答案的索引
    _correctAnswerIndex = indexes.indexOf(0);
  }

  @override
  void dispose() {
    _audioPlayer.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.pop(context),
        ),
        title: const Text('练习'),
        actions: [
          IconButton(
            icon: const Icon(Icons.settings),
            onPressed: () {
              // TODO: 实现设置功能
            },
          ),
        ],
      ),
      body: Column(
        children: [
          _buildHeader(),
          const SizedBox(height: 20),
          Expanded(
            child: AnimatedSwitcher(
              duration: const Duration(milliseconds: 300),
              transitionBuilder: (Widget child, Animation<double> animation) {
                return FadeTransition(
                  opacity: animation,
                  child: child,
                );
              },
              child: _buildImageGrid(key: ValueKey(_currentQuestionIndex)),
            ),
          ),
          _buildPaginationControls(), // 添加翻页控件
        ],
      ),
    );
  }

  Widget _buildHeader() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            'Mosquito',
            style: Theme.of(context).textTheme.headlineMedium?.copyWith(
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '蚊子',
            style: Theme.of(context).textTheme.titleLarge?.copyWith(
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 12),
          IconButton(
            icon: const Icon(Icons.volume_up),
            iconSize: 32,
            color: Theme.of(context).primaryColor,
            onPressed: () {
              _audioPlayer.play(AssetSource('audio/mosquito.mp3'));
            },
          ),
        ],
      ),
    );
  }

  Widget _buildImageGrid({Key? key}) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20.0),
      child: GridView.builder(
        key: key,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 3/4,
          crossAxisSpacing: 16,
          mainAxisSpacing: 16,
        ),
        itemCount: 4,
        itemBuilder: (context, index) {
          bool isSelected = _selectedIndex == index;
          bool showResult = _hasAnswered && isSelected;
          bool isCorrect = index == _correctAnswerIndex;

          return GestureDetector(
            onTap: () {
              if (!_hasAnswered) {
                setState(() {
                  _selectedIndex = index;
                  _hasAnswered = true;
                });
              }
            },
            child: AnimatedContainer(
              duration: const Duration(milliseconds: 300),
              decoration: BoxDecoration(
                border: Border.all(
                  color: showResult
                      ? (isCorrect ? Colors.green : Colors.red)
                      : (isSelected ? Theme.of(context).primaryColor : Colors.grey[300]!),
                  width: isSelected ? 3 : 1,
                ),
                borderRadius: BorderRadius.circular(12),
                boxShadow: isSelected
                    ? [
                        BoxShadow(
                          color: showResult
                              ? (isCorrect ? Colors.green.withOpacity(0.3) : Colors.red.withOpacity(0.3))
                              : Theme.of(context).primaryColor.withOpacity(0.3),
                          blurRadius: 8,
                          offset: const Offset(0, 2),
                        ),
                      ]
                    : null,
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(11),
                child: Stack(
                  children: [
                    Positioned.fill(
                      child: Image.asset(
                        _images[index],
                        fit: BoxFit.cover,
                      ),
                    ),
                    // 可选：添加选中效果
                    if (showResult)
                      Positioned(
                        right: 8,
                        top: 8,
                        child: Container(
                          padding: const EdgeInsets.all(4),
                          decoration: BoxDecoration(
                            color: isCorrect ? Colors.green : Colors.red,
                            shape: BoxShape.circle,
                          ),
                          child: Icon(
                            isCorrect ? Icons.check : Icons.close,
                            color: Colors.white,
                            size: 20,
                          ),
                        ),
                      ),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  // 翻页控件
  Widget _buildPaginationControls() {
    final primaryColor = Theme.of(context).primaryColor;
    
    return Container(
      padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 上一题按钮
          _buildNavigationButton(
            icon: Icons.arrow_back_ios_rounded,
            onPressed: _currentQuestionIndex > 0 ? _previousQuestion : null,
            isLeft: true,
          ),
          
          // 题号显示
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
            decoration: BoxDecoration(
              color: Colors.grey[100],
              borderRadius: BorderRadius.circular(20),
            ),
            child: Text(
              '${_currentQuestionIndex + 1}/$_totalQuestions',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: primaryColor,
              ),
            ),
          ),
          
          // 下一题按钮
          _buildNavigationButton(
            icon: Icons.arrow_forward_ios_rounded,
            onPressed: _currentQuestionIndex < _totalQuestions - 1 ? _nextQuestion : null,
            isLeft: false,
          ),
        ],
      ),
    );
  }

  // 导航按钮组件
  Widget _buildNavigationButton({
    required IconData icon,
    required VoidCallback? onPressed,
    required bool isLeft,
  }) {
    final primaryColor = Theme.of(context).primaryColor;
    final isEnabled = onPressed != null;

    return Container(
      width: 48,
      height: 48,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        gradient: isEnabled
            ? LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  primaryColor.withOpacity(0.9),
                  primaryColor,
                ],
              )
            : LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Colors.grey[300]!,
                  Colors.grey[400]!,
                ],
              ),
        boxShadow: isEnabled
            ? [
                BoxShadow(
                  color: primaryColor.withOpacity(0.3),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ]
            : null,
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: onPressed,
          borderRadius: BorderRadius.circular(24),
          child: Icon(
            icon,
            color: isEnabled ? Colors.white : Colors.grey[500],
            size: 24,
          ),
        ),
      ),
    );
  }

  // 上一题方法
  void _previousQuestion() {
    if (_currentQuestionIndex > 0) {
      setState(() {
        _currentQuestionIndex--;
        _resetQuestion();
      });
    }
  }

  // 下一题方法
  void _nextQuestion() {
    if (_currentQuestionIndex < _totalQuestions - 1) {
      setState(() {
        _currentQuestionIndex++;
        _resetQuestion();
      });
    }
  }

  // 重置当前题目状态
  void _resetQuestion() {
    _selectedIndex = null;
    _hasAnswered = false;
    // 重新打乱图片顺序
    final random = Random();
    final indexes = List.generate(4, (index) => index);
    indexes.shuffle(random);
    
    final shuffledImages = indexes.map((i) => _images[i]).toList();
    _images.clear();
    _images.addAll(shuffledImages);
    
    _correctAnswerIndex = indexes.indexOf(0);
  }
}
